import React from 'react';
import { Spin } from 'antd';
import { features, useTablePipeline } from 'ali-react-table';
import moment from 'moment';
import { connect } from 'umi';
import { HttpCode } from '#/utils/contacts.js';
import { PageLoading, TRDefault } from '@/components/index.js';
import { TjTable, useTRState } from '@/pages/ETrade/components';
import { FileTextOutlined, PlusCircleOutlined } from '#/utils/antdIcons';
import { useStaticState } from '#/utils/trHooks';
import { TRMessage } from '#/components';

import { getPhoneNumberInformationList, deletePhone } from './services.js';
import { tableColumns } from './helper';
import OperateLogModal from './componets/OperateLogModal';
import EditorModel from './componets/EditorModel';
import styles from './index.less';

const PhoneNumberInformation = ({ menuCode, buttonPermissions }) => {
  /** data */
  const [state, setState] = useTRState({
    // 初始化三件套
    spinning: true,
    error: '',
    power: buttonPermissions.find((item) => item.menuCode === 'MessageView'),
    // 表单
    formValues: null,
    loading: true,
    // 数据
    tableData: [],
  });

  const staticData = useStaticState({
    operatList: [
      {
        code: 'edit',
        name: '编辑',
      },
      {
        code: 'delete',
        name: '删除',
      },
    ],
    btnList: [
      {
        code: 'history',
        name: '变更记录',
        icon: <FileTextOutlined style={{ marginRight: 4 }} />,
      },
      {
        code: 'add',
        name: '新增',
        icon: <PlusCircleOutlined style={{ marginRight: 4 }} />,
      },
    ],
  });

  React.useEffect(async () => {
    await init();
    setState({ loading: false });
  }, []);

  /** apis */
  const init = async () => {
    setState({
      spinning: true,
    });
    const res = await getPhoneNumberInformationList();
    let error = '';
    if (res?.statusCode === HttpCode.SUCCESS) {
      setState({
        tableData: res.data || [],
      });
    } else {
      error = res?.message || '系统异常';
    }
    setState({
      error,
      spinning: false,
    });
  };

  const operatHanlder = async (code, data) => {
    switch (code) {
      case 'add':
      case 'edit': {
        const res = await EditorModel.show({ data, code });
        if (res.index) {
          init();
        }
        break;
      }
      case 'delete': {
        setState({ spinning: true });
        const res = await deletePhone(data?.id);
        if (res?.statusCode === HttpCode.SUCCESS) {
          await init();
          TRMessage.success('删除成功');
        } else {
          TRMessage.error(res?.message || '删除失败');
        }
        setState({ spinning: false });
        break;
      }
      case 'history': {
        await OperateLogModal.show({});
        break;
      }
    }
  };

  const getTableColumns = () => {
    return tableColumns.map((t, i) => {
      switch (t.code) {
        case 'status':
          t.render = (v) =>
            v ? (
              <span key={i} style={{ color: '#1CA773', fontSize: 12 }}>
                启用
              </span>
            ) : (
              <span key={i} style={{ color: '#FF5353', fontSize: 12 }}>
                停用
              </span>
            );
          break;
        case 'operation':
          t.render = (v, record) => (
            <div className={styles.operation} key={i}>
              {staticData.operatList.map((t, i) => (
                <a
                  style={{ color: 'var(--bd-primary)', fontSize: 12 }}
                  onClick={() => {
                    operatHanlder(t.code, record);
                  }}
                  key={i}
                >
                  {t.name}
                </a>
              ))}
            </div>
          );
          break;
      }
      return t;
    });
  };
  // /** render */
  const pipeline = useTablePipeline({ components: {} })
    .input({ dataSource: state.tableData, columns: getTableColumns() })
    .primaryKey('id');
  // .appendRowPropsGetter((record, rowIndex) => {
  //   const color = rowIndex % 2 == 0 ? '#222629' : '#2D3133';
  //   return {
  //     style: { '--bgcolor': color, '--hover-bgcolor': color },
  //   };
  // });

  const renderContent = () => {
    if (!state.tableData?.length) return <TRDefault type="empty" />;
    return <TjTable {...pipeline.getProps()} useVirtual={false} />;
  };

  if (state.loading) return <PageLoading />;
  if (state.error) return <TRDefault type="error" message={state.error} />;
  // if (!state.power) return <TRDefault type="lock" />;
  return (
    <Spin spinning={state.spinning}>
      <div className={styles.container}>
        <div className={styles.main}>
          <div className={styles.inhead}>
            <div className={styles.inhead__left}>手机号信息</div>
            <div className={styles.inhead__right}>
              {staticData.btnList.map((t, i) => (
                <div
                  key={i}
                  className={styles.inhead__right__item}
                  onClick={() => {
                    operatHanlder(t.code);
                  }}
                >
                  {t.icon}
                  {t.name}
                </div>
              ))}
            </div>
          </div>
          <div className={styles.inbody}>{renderContent()}</div>
        </div>
      </div>
    </Spin>
  );
};

export default connect(({ global }) => ({
  menuCode: global.configure.menuCode,
  buttonPermissions: global.configure.buttonPermissions,
}))(PhoneNumberInformation);
